import os
import logging
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime


def setup_logger(name: str = "jpy_rate") -> logging.Logger:
    """设置日志记录器"""
    
    # 创建logs目录
    log_dir = "./logs"
    os.makedirs(log_dir, exist_ok=True)
    
    # 创建logger
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)
    
    # 避免重复添加handler
    if logger.handlers:
        return logger
    
    # 文件handler - 按小时轮转
    log_file = os.path.join(log_dir, "jpy-{}.log".format(
        datetime.now().strftime("%Y%m%d_%H")
    ))
    
    file_handler = TimedRotatingFileHandler(
        filename=log_file,
        when='H',  # 按小时轮转
        interval=1,
        backupCount=168,  # 保留7天(7*24小时)
        encoding='utf-8'
    )
    
    # 控制台handler
    console_handler = logging.StreamHandler()
    
    # 日志格式
    formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s [%(name)s] %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    
    # 添加handlers
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger
